<template>
  <div class="role-detail">
    <el-dialog
      :title="roleDialog.title"
      :visible.sync="roleDialog.show"
      :close-on-click-modal="false"
      width="500px"
    >
      <el-form
        ref="roleForm"
        :model="roleDialog.form"
        label-width="70px"
        label-position="left"
        size="small"
      >
        <el-form-item :label="$t('role.title')">
          <el-input v-model="roleDialog.form.Title" />
        </el-form-item>
        <el-form-item :label="$t('role.desc')">
          <el-input v-model="roleDialog.form.Desc" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button plain @click="roleDialog.show=false">{{ $t('role.cancel') }}</el-button>
        <el-button
          type="primary"
          :disabled="roleDialog.loading"
          :loading="roleDialog.loading"
          @click="onConfirmRole"
        >
          {{ $t('role.submit') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { createRole, updateRole } from '@/api/role'

export default {
  name: 'RoleDetail',
  props: {
    value: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      roleDialog: {
        show: false,
        title: '',
        form: {}
      }
    }
  },
  watch: {
    value: {
      handler(val) {
        this.roleDialog = val
      },
      deep: true,
      immediate: true
    },
    roleDialog: {
      handler(val) {
        this.$emit('input', val)
        this.$emit('on-change', val)
      },
      deep: true
    }
  },
  methods: {
    onConfirmRole() {
      this.$refs['roleForm'].validate(async(valid) => {
        if (valid) {
          try {
            this.$set(this.roleDialog, 'loading', true)
            const data = this.roleDialog.status === 'add' ? await createRole(this.roleDialog.form) : await updateRole(
              this.roleDialog.form)
            if (data.Message === 'ok') {
              this.$notify({
                title: this.$t('role.success'),
                message: this.roleDialog.status === 'add' ? this.$t('role.addSuccessAlert') : this.$t(
                  'role.editSuccessAlert'),
                type: 'success',
                duration: 2000
              })
              this.$set(this.roleDialog, 'show', false)
              this.$emit('refresh-list')
            }
          } catch (e) {
            console.log(e)
          } finally {
            this.$set(this.roleDialog, 'loading', false)
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
